package com.lou1052.redis.jedis.action.script;

import com.google.common.collect.Lists;
import com.lou1052.redis.jedis.api.ScriptCommands;

import java.util.List;

/**
 * 存在且匹配才删除对象
 *if (cache.containsKey(key) && equals(cache.get(key), oldValue) {
 *   cache.remove(key);
 *   return true;
 * } else {
 *   return false;
 * }
 * Created with IntelliJ IDEA.
 * User: liuqing
 * Date: 2015/11/16
 * Time: 21:51
 * To change this template use File | Settings | File Templates.
 */
public class RemoveEqObjectAction extends ScriptAction<Boolean>{
    private static final String SCRIPT="local v=redis.call('get',KEYS[1]);if v and v==ARGV[1] then redis.call('del',KEYS[1]);return 1;else return 0;end";

    private final Object newValue;

    public RemoveEqObjectAction(String key ,Object newValue) {
        super(key);
        this.newValue=newValue;
    }

    @Override
    public Boolean callOn(ScriptCommands scriptCommands){
        List<Object> params = Lists.newArrayList(newValue);
        return (Long)scriptCommands.eval(SCRIPT,getKey(),params)>0;
    }
}
